package com.singzi.leetcode.N100;

/**
 * 合并几个链表
 */

public class T0023 {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(6);
        ListNode l1 = new ListNode(5, listNode);
        ListNode listNode2 = new ListNode(8);
        ListNode l2 = new ListNode(4, listNode2);
        ListNode list;
        Solution0023 solution0023 = new Solution0023();
       ListNode[]listNodes = {
                l2,l1
        };
        list = solution0023.MergeLists(listNodes);
        while (list!=null){
            System.out.println(list.val);
            list = list.next;
        }
    }
}
class Solution0023{
    public ListNode MergeLists(ListNode[] lists){
        if(lists.length == 0){
        ListNode list = null;
        return list;
        }
        if(lists.length == 1){
            return lists[0];
        }

        ListNode list = MergeList(lists[0], lists[1]);
        for(int i = 2;i < lists.length;i++){
            list = MergeList(list, lists[i]);
        }
        return list;
    }
    public ListNode MergeList(ListNode l1, ListNode l2){

        ListNode p = new ListNode(), t;
        t = p;
        while(l1 != null && l2 != null){
            if(l1.val> l2.val){
                t.next = l2;
                l2 = l2.next;
            }
            else {
                t.next = l1;
                l1 = l1.next;
            }
            t = t.next;
        }
        t.next = (l1 != null) ? l1 : l2;
        return p.next;
    }
}
